import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import NotesList from '../views/NotesList.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/notes'
    },
    {
      path: '/auth',
      name: 'auth',
      component: () => import('../views/AuthView.vue'),
      meta: { requiresGuest: true }
    },
    {
      path: '/notes',
      name: 'notes',
      component: NotesList,
      meta: { requiresAuth: true }
    },
    {
      path: '/editor/:id?',
      name: 'editor',
      component: () => import('../views/NoteEditor.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/settings',
      name: 'settings',
      component: () => import('../views/Settings.vue'),
      meta: { requiresAuth: true }
    },
  ],
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  
  // 初始化认证状态（仅在首次访问时）
  if (!authStore.user && authStore.getToken()) {
    try {
      await authStore.initAuth()
    } catch (error) {
      console.error('认证初始化失败:', error)
    }
  }

  const requiresAuth = to.meta.requiresAuth
  const requiresGuest = to.meta.requiresGuest
  const isAuthenticated = authStore.isAuthenticated

  if (requiresAuth && !isAuthenticated) {
    // 需要认证但未登录，跳转到登录页
    next({ name: 'auth', query: { redirect: to.fullPath } })
  } else if (requiresGuest && isAuthenticated) {
    // 需要游客状态但已登录，跳转到笔记列表
    next({ name: 'notes' })
  } else {
    next()
  }
})

export default router
